package com.yami.shop.admin.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.service.OrderItemService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.SkuService;
import com.yami.shop.sys.service.SysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@EnableScheduling//开启定时任务
@Component
public class MyTask {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OrderService orderService;
    @Autowired
    private ProductService productService;
    @Autowired
    private SkuService skuService;
    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private Environment environment;
/*
    @Scheduled(fixedDelay = 3000)
    public void myRun(){
        String str = sysConfigService.getValue("cancelOrderTime");
        if(str==null || str.equals("")){
            str="720";
        }
        Integer cancelOrderTime=Integer.parseInt(str);
        if (cancelOrderTime==null){
            cancelOrderTime=-720;
        }else{
            cancelOrderTime=(-1)*cancelOrderTime;
        }
        logger.info("==============  "+cancelOrderTime);
    }

 */
    @Scheduled(fixedDelay = 600000)
    public void cancelOrder(){
        String[] activeProfiles = environment.getActiveProfiles();

        if("prod".equals(activeProfiles[0])) {
            Date now = new Date();
            logger.info("取消超时未支付订单。。。");
            // 获取30分钟之前未支付的订单
            //List<Order> orders = orderService.listOrderAndOrderItems(OrderStatus.UNPAY.value(), DateUtil.offsetMinute(now, -30));
            String str = sysConfigService.getValue("cancelOrderTime");
            if (str == null || str.equals("")) {
                str = "720";
            }
            Integer cancelOrderTime = Integer.parseInt(str);
            if (cancelOrderTime == null) {
                cancelOrderTime = -720;
            } else {
                cancelOrderTime = (-1) * cancelOrderTime;
            }
            List<Order> orders = orderService.listOrderAndOrderItems(OrderStatus.UNPAY.value(), DateUtil.offsetMinute(now, cancelOrderTime));
            if (CollectionUtil.isEmpty(orders)) {
                return;
            }
            orderService.cancelOrders(orders);
            try {
                for (Order order : orders) {
                    try {
                        Map<String, Object> p = new HashMap<>();
                        p.put("pOrderNumber", order.getOrderNumber());
                        orderItemService.CancelOrderBackBalance(p);
                    } catch (Exception e) {
                        logger.error(e.getMessage());
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                e.printStackTrace();
            }
            for (Order order : orders) {
                List<OrderItem> orderItems = order.getOrderItems();
                for (OrderItem orderItem : orderItems) {
                    productService.removeProductCacheByProdId(orderItem.getProdId());
                    skuService.removeSkuCacheBySkuId(orderItem.getSkuId(), orderItem.getProdId());
                }
            }
        }
    }
}
